using System;
using XcoAppSpaces.Transport.Sockets.Auth.Contract.DoClientHandshake;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	class ReceiveChallenge : IReceiveChallenge
	{
		private int challengeLength;
		//private int readTimeoutSeconds;

		public void In_Connection(ConnectionInfo conn)
		{
			//Console.WriteLine("ReceiveChallenge.In_Connection");
#if !SILVERLIGHT

			try
			{
				var challenge = new byte[challengeLength];
				conn.Reader.Read(challenge); //NetworkStreamExtensions.ReadExactly(conn.InputStream, challengeLength);
				Out_ValidConnection(new ConnectionWithChallenge { Connection = conn, Challenge = challenge });
			}
			catch
			{
				Out_InvalidConnection(conn.Client);
			}
#else
			conn.Client.Socket.Receive(challengeLength, (s, e) =>
			{
				if (e.SocketError == SocketError.Success)
					Out_ValidConnection(new ConnectionWithChallenge { Connection = conn, Challenge = e.Buffer });
				else
					Out_InvalidConnection(conn.Client);
			});
#endif
		}

		public event ValidChallengeConnectionHandler Out_ValidConnection;

		public event TcpClientHandler Out_InvalidConnection;

		public void Inject(SecuritySettings securitySettings)
		{
			challengeLength = securitySettings.ChallengeLength;
			//readTimeoutSeconds = securitySettings.SecondsAfterInvalidConnectionIsClosed;
		}
	}
}
